package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @package com.leyou.item.service
 * @description:
 * @author: 86157
 * @date 2019/6/26 21:51
 * @version: V1.0
 */
@Service
public class GoodsService {


    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        //1.分页
        PageHelper.startPage(page, rows);
        //2.过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        //2.1搜索条件过滤
        if (StringUtils.isNoneBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }

        //2.2上下架过滤
        criteria.andEqualTo("saleable", saleable);

        //2.3默认时间排序
        example.setOrderByClause("update_time DESC");


        //3.查询结果
        List<Spu> spus = spuMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //4.封装分页结果
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);

        //DTO转换
        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(spus, SpuDTO.class);

        //处理分类名称和品牌名称
        handleCategotyAndBrandName(spuDTOS);

        return new PageResult<>(pageInfo.getTotal(), spuDTOS);

    }

    private void handleCategotyAndBrandName(List<SpuDTO> spuDTOS) {
        for (SpuDTO spuDTO : spuDTOS) {
            //查询分类
            String categoryName = categoryService.queryCategoryByCid(spuDTO.getCategoryIds()).stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
            //查询品牌
            BrandDTO brandDTO = brandService.queryBrand(spuDTO.getBrandId());
            spuDTO.setBrandName(brandDTO.getName());
        }
    }


    /**
     * 新增商品
     *
     * @param spuDTO
     * @return
     */
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        //从spuDto中取出商铺信息
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);

        //1.新增spu数据
        spu.setId(null);
        spu.setSaleable(false);
        spu.setCreateTime(null);

        int count = spuMapper.insertSelective(spu);

        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //2.新增spuDetail数据
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();

        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        //获取spu表中新增数据的主键自增长id
        spuDetail.setSpuId(spu.getId());

        count = detailMapper.insertSelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);

        }

        //新增sku数据
        List<SkuDTO> skus = spuDTO.getSkus();

        List<Sku> skuList = BeanHelper.copyWithCollection(skus, Sku.class);

        for (Sku sku : skuList) {
            sku.setSpuId(spu.getId());
            sku.setEnable(false);
        }
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /**
     * 修改商品前下架商品
     *
     * @param
     * @return
     */
    public void updateSaleable(Long id, Boolean saleable) {

        //修改spu中下架
        Spu spu = new Spu();
        spu.setSaleable(saleable);
        spu.setId(id);
        int i = spuMapper.updateByPrimaryKeySelective(spu);
        if (i != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //修改sku中enable下架
        //准备更新数据
        Sku sku = new Sku();
        sku.setEnable(saleable);

        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);

        //修改数据
        i = skuMapper.updateByExampleSelective(sku, example);

        //根据spu的id查询当前数据个数
        int count = skuMapper.selectCountByExample(example);
        if (count != i) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }


    }

    public SpuDetailDTO querySpuDetail(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);

        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);

    }


    /**
     * 根据spuid查询sku
     *
     * @param id
     * @return
     */
    public List<SkuDTO> querySku(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> skuList = skuMapper.select(sku);

        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }

    /**
     * 修改商品
     *
     * @param spuDTO
     */
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        //1.更新sku
        //1.1删除sku
        Long id = spuDTO.getId();
        if (id == null) {
            //请求参数错误
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //1.2根据spuid删除sku
        Sku sku = new Sku();
        sku.setSpuId(id);
        //查询spuid数量,若数量为0，则不需要对sku进行删除
        int i = skuMapper.selectCount(sku);
        if (i > 0) {
            int delete = skuMapper.delete(sku);
            if (i != delete) {
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }

        //2.更新spu

        //初始化更新数据
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(false);
        spu.setCreateTime(null);
        spu.setUpdateTime(null);
        int i1 = spuMapper.updateByPrimaryKeySelective(spu);

        if (i1 != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }


        //3.更新spudetail
        SpuDetail spuDetail1 = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail1.setUpdateTime(null);

        spuDetail1.setCreateTime(null);
        int i2 = detailMapper.updateByPrimaryKeySelective(spuDetail1);
        if (i2 != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }


        //4.新增sku,根据spuid新增
        List<SkuDTO> skus = spuDTO.getSkus();
        List<Sku> list = BeanHelper.copyWithCollection(skus, Sku.class);

        for (Sku sku1 : list) {
            //使sku下架
            sku1.setEnable(false);
            sku1.setSpuId(id);
        }
        int i3 = skuMapper.insertList(list);
        if (i3 != list.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }
}